package thread;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author: feiwang_6
 * @create: 2019/12/4 19:15
 * @description:
 */
public class Counter {
    
    private int count = 0;
    private AtomicInteger atomicI = new AtomicInteger(0);
    
    /**
     * 使用CAS实现线程安全计数器
     */
    public void safeCount(AtomicInteger atomicI) {
        for (; ; ) {
            int i = atomicI.get();
            boolean suc = atomicI.compareAndSet(i, ++i);
            if (suc) {
                break;
            }
        }
    }
    
    public void count(){
        count++;
    }
    
    @Test
    public void testMath(){
        final Counter cas = new Counter();
        List<Thread> ts = new ArrayList<Thread>(600);
        for (int j = 0; j < 10000; j++) {
            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i < 10; i++) {
                        cas.safeCount(atomicI);
                        cas.count();
                    }
                }
            });
            ts.add(t);
        }
        for (Thread t : ts) {
            t.start();
        }
        // 等待所有线程执行完成
        for (Thread t : ts) {
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("原子性: " + atomicI.get());
        System.out.println("非原子性: " + cas.count);
    }
}
